//
//  DSPNetTools.swift
//  SWweibo
//
//  Created by 杜守鹏 on 15/12/30.
//  Copyright © 2015年 杜守鹏. All rights reserved.
//

import UIKit
import AFNetworking

class DSPNetTools: AFHTTPSessionManager {
    static let sharedTools:DSPNetTools = {
        let instance = DSPNetTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    typealias DSPFinished = (response:AnyObject?,error:NSError?)->()
    func getRequest(URLString: String, parameters: AnyObject?,finished:DSPFinished){
     
        let success = {(dataTask: NSURLSessionDataTask?,response: AnyObject?) -> Void in
            finished(response: response, error: nil)
        }
        
        let failure = {( dataTak: NSURLSessionDataTask?,error: NSError )->Void in
            finished(response: nil, error: error)
        }
        GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
    }
   
    func POSTrequest(URLString: String, parameters: AnyObject?,finished:DSPFinished){
        
        let success = {(dataTask:NSURLSessionDataTask,response:AnyObject?)->Void in
            finished(response: response, error: nil)
        }
        
        let failure = {(dataTask:NSURLSessionDataTask?,error:NSError)->Void in
         finished(response: nil, error: error )
        }
        POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
    }
}


extension DSPNetTools{
    
    func loadAccessTocken(code:String,finished:DSPFinished){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        var dict = [String:NSObject]()
        dict["client_id"]=WB_APPKEY
        dict["client_secret"]=WB_SECRET
        dict["grant_type"]="authorization_code"
        dict["code"]=code
        dict["redirect_uri"]=WB_REGIRECTURI
        
        POSTrequest(urlString, parameters: dict, finished: finished)
    }
    
    func loadUserImage(access_token:String,uid:String,finished:DSPFinished){
       let urlString = "https://api.weibo.com/2/users/show.json"
        var parameters = [String:AnyObject]()
        parameters["access_token"]=access_token
        parameters["uid"]=uid
        getRequest(urlString, parameters: parameters, finished: finished)
    }
    
}